/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pl.cezary.butler.walili.server.utils;

import java.io.IOException;
import java.io.InputStream;
import pl.cezary.butler.walili.client.ClientApp;
import pl.cezary.butler.walili.client.network.INetworkStats;

/**
 *
 * @author Czarek
 */
public class MonitoredInputStream extends InputStream{
    
    private static final INetworkStats NETWORK_STATS = ClientApp.getContext().getBean(INetworkStats.class);    
    private static final int REPORT_COUNT = 1024;
    
    private final InputStream source;
    private final INetworkStats networkStats;
    
    private int count = 0;

    public MonitoredInputStream(InputStream source, INetworkStats networkStats) {
        this.source = source;
        this.networkStats = networkStats;
    }

    public MonitoredInputStream(InputStream source) {
        this(source,NETWORK_STATS);
    }        

    @Override
    public int read() throws IOException {
        ++count;
        if(count==REPORT_COUNT){
            networkStats.read(count);
            count=0;
        }
        return source.read();
    }

    @Override
    public void close() throws IOException {
        networkStats.read(count);
        super.close();
    }
    
    
}
